<template>
  <div>
    <BreadCrumbShow />
    <!-- <PageTitle pageTitle="永久下架记录" /> -->

    <div class="search-list">
      <el-form
        :inline="true"
        :model="searchForm"
        class="form-inline"
        @submit.native.prevent
      >
        <el-form-item>
          <el-input
            size="medium"
            placeholder="请输入窍编码进行搜索"
            v-model.trim="searchForm.keyword"
            class="input-with-select"
            clearable
            @keyup.enter.native="
              () => {
                pageNum = 1;
                getOffshelfLogList();
              }
            "
          >
            <el-button
              slot="append"
              type="primary"
              @click="
                () => {
                  pageNum = 1;
                  getOffshelfLogList();
                }
              "
              >筛选</el-button
            >
          </el-input>
        </el-form-item>
      </el-form>
      <div class="search-right">
        <!-- <ExcelButton @outExcel="outExcel" :isExcelLoading="isExcelLoading" /> -->

        <el-button size="small" @click="goApply" v-if="showApply">
          <div class="btn">
            <i class="el-icon-back"></i>
            <span class="text">返回申请界面</span>
          </div>
        </el-button>
        <el-button size="small" @click="goApprove" v-if="showApprove">
          <div class="btn">
            <span class="text">去下架审批界面</span>
          </div>
        </el-button>
      </div>
    </div>

    <!-- table样式展示 -->
    <LogTable
      refName="applyReadLog"
      @pageChange="pageChange"
      :type="1"
      :data-source="backLogList"
      :data-config="tableConfig"
      :total="total"
      :pageSize="pageSize"
      :pageNum="pageNum"
      :isLoading="isLoading"
    >
      <template #statusHeader>
        <div class="header-select">
          <el-select
            v-model="statusHeader"
            placeholder="状态"
            size="medium"
            @change="changeSelect"
            clearable
          >
            <el-option
              v-for="item in tableConfig.filter((e) => e.prop == 'status')[0]
                .selectOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
      </template>

      <template #boxInfoHeader>
        <div class="header-select header-select-first">
          <div class="left">
            <el-select
              v-model="boxInfoHeader"
              placeholder="订单详情"
              size="medium"
              @change="changeSelect"
            >
              <el-option
                v-for="item in tableConfig.filter((e) => e.prop == 'boxInfo')[0]
                  .selectOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>

            <!-- <span>订单详情</span> -->
          </div>
          <div class="right"></div>
        </div>
      </template>

      <template #applyNameHeader>
        <div class="header-select">
          <el-select
            v-model="applyNameHeader"
            placeholder="申请人"
            size="medium"
            @change="changeSelect"
            clearable
          >
            <el-option
              v-for="item in tableConfig.filter((e) => e.prop == 'applyName')[0]
                .selectOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <div>{{ item.label }}{{item.phone ? '(' + item.phone + ')' : item.phone}}</div>
            </el-option>
          </el-select>
        </div>
      </template>

      <template #rowHead="{ row }">
        <div class="mar-right">
          订单号：
          <span class="hover-change" @click="goOrderDetail(row)">{{
            row.orderNumber
          }}</span>
        </div>
        <div class="mar-right">
          窍数量：
          <span>{{ row.boxInfoLength }}</span>
        </div>
        <div class="mar-right">{{ row.createdOn }}</div>
      </template>

      <div slot="boxInfo"></div>
      <template #boxInfo="{ row }">
        <div class="box-code">
          <div
            v-for="(box, index) in row.boxInfo"
            :key="index"
            :class="[
              'box',
              index !== row.boxInfo.length - 1 ? ' border-bottom' : '',
            ]"
          >
            <div class="box-code-left" @click="goBoxDetail(box)">
              <BoxIconShow :rowInfo="box" />
            </div>

            <div class="box-operate">
              <!-- 展示窍状态 -->
              <span v-if="box.status !== 0">
                {{ commonFun.getLabel(orderStatus, box.status) }}</span
              >

              <el-button
                v-if="
                  box.status == 0 && row.status == 0 && row.boxInfo.length > 1 && row.canPeopleCancel
                "
                type="primary"
                size="mini"
                @click.native="cancelBox(row, box)"
                >取消永久下架</el-button
              >
            </div>
          </div>
          <i v-if="row.currentPage < row.totalPage" class="el-icon-d-arrow-right show-more" @click="showMore(row)"></i>
        </div>
      </template>

      <template #contactName="{ row }">
        <div class="cell-popover">
          <el-popover placement="top" width="250" trigger="hover">
            <div>
              <div class="popover-item">
                <i class="el-icon-user-solid"></i>
                <span>{{ row.contactName }}</span>
              </div>
              <div class="popover-item" v-if="row.address">
                <i class="el-icon-location"></i>
                <span>
                  {{ row.address ? row.address : "无" }}
                </span>
              </div>
              <div class="popover-item">
                <i class="el-icon-phone"></i>
                <span>{{ row.contactMobile }} </span>
              </div>
            </div>

            <div slot="reference" class="popover-reference">
              {{ row.contactName }} <i class="el-icon-user-solid"></i>
            </div>
          </el-popover>
        </div>
      </template>
      <template #applyName="{ row }">
        <div class="cell-tag">
          <div>
            {{ row.userName }}
          </div>
          <div>
            {{ row.mobile }}
          </div>
        </div>
      </template>

      <template #status="{ row }">
        <div class="cell-tag">
          <span>{{ commonFun.getLabel(orderStatus, row.status) }}</span>
        </div>
      </template>

      <template #detail="{ row }">
        <div class="cell-tag">
          <div>
            <el-button type="text" size="mini" @click="toshowVoucher(1, row)"
              ><i class="el-icon-folder-opened"></i> 下架凭证</el-button
            >
          </div>
          <div v-if="row.status === 3">
            <el-button type="text" size="mini" @click="toshowVoucher(2, row)"
              ><i class="el-icon-folder-opened"></i> 取消凭证</el-button
            >
          </div>
          <div v-if="row.status === 2">
            <!-- 完成时有 -->
            <el-button type="text" size="mini" @click="toshowVoucher(3, row)"
              ><i class="el-icon-folder-opened"></i> 销毁凭据</el-button
            >
          </div>
        </div>
      </template>
    </LogTable>

    <VoucherShow
      :title="voucherTitle"
      :isShowVoucher.sync="isShowVoucher"
      :voucherList="voucherList"
      @closeDialog="closeVoucherDialog"
    />

  </div>
</template>

<script>
import { orderStatus } from "@/utils/dictionary.js";
import axios from "axios";
import Cookies from "js-cookie";
import LogTable from "@/components/table/LogTable.vue";
import VoucherShow from "../access-manage/components/VoucherShow";
import BoxIconShow from "@/components/public-style/BoxIconShow";
import ExcelButton from "@/components/public-style/ExcelButton";
import {
  getOrderList,
  getOrderListCount,
  cancelReadOrder,
  getApplyUserList,
  getOrderBoxList,
  getOrderFileList,
} from "../../api/access-manage/index";
import PageTitle from "@/components/PageTitle";
export default {
  name: "backLog",
  components: {
    LogTable,
    VoucherShow,
    BoxIconShow,
    ExcelButton,
    PageTitle,
  },
  data() {
    return {
      orderStatus: orderStatus,
      voucherTitle: "凭证",
      isShowVoucher: false,
      voucherList: [],

      statusHeader: undefined,
      boxInfoHeader: "0",
      applyNameHeader: undefined,

      searchForm: {
        keyword: "",
      },

      tableConfig: [
        {
          prop: "boxInfo",
          label: "窍详细",
          width: 700,
          selectOption: [],
        },

        {
          prop: "contactName",
          label: "联系人",
        },
        {
          prop: "applyName",
          label: "申请人",
          // width: 130,
          selectOption: [],
        },

        {
          prop: "status",
          label: "状态",
          // width: 130,
          selectOption: [
            { label: "全部状态", value: undefined },
            { label: "待处理", value: "0" },
            { label: "处理中", value: "1" },
            { label: "已完成", value: "2" },
            { label: "已取消", value: "3" },
            { label: "已合并", value: "5" }
          ],
        },
        {
          prop: "detail",
          label: "详情",
        },
      ],
      backLogList: [],
      total: 0,
      pageSize: 10,
      pageNum: 1,
      isLoading: false,
      exportData: { type: 3 },
      isExcelLoading: false,
      showApprove: false,
      showApply: false
    };
  },
  created() {
    const currentStorage = JSON.parse(localStorage.getItem("localUserInfo"))
    let authIdArr = currentStorage && currentStorage.authIdArr || []
    this.showApprove = authIdArr.includes(1060200);
    this.showApply = authIdArr.includes(1060100);
    // 只有当永久下架的批准界面允许显示时显示

    // 获取 全部订单申请人
    getApplyUserList().then((res) => {
      let userList = [{ label: "申请人", value: undefined }];

      res.data.map((e) => {
        userList.push({ label: e.realName, phone: e.mobile, value: e.id });
      });

      this.tableConfig.filter((e) => e.prop == "applyName")[0].selectOption =
        userList;
    });
    this.tableConfig.filter((e) => e.prop == "boxInfo")[0].selectOption = this.commonFun.getBoxInfoSelectOption()
      // this.setTimeRange();
  },
  mounted() {
    this.getOffshelfLogList();
  },
  methods: {
    // // 设置时间搜索区间
    // setTimeRange() {
    //   const boxInfoSelectOption = [
    //     {
    //       label: "近三个月",
    //       value: "0",
    //       beginTime: this.$moment().subtract(3, "months").valueOf(),
    //       endTime: this.$moment().endOf('day').valueOf(),
    //     },
    //     {
    //       label: "今年",
    //       value: "1",
    //       beginTime: this.$moment().startOf("year").valueOf(),
    //       endTime: this.$moment().endOf("year").valueOf(),
    //     },
    //     {
    //       label: "2024年",
    //       value: "9",
    //       beginTime: this.$moment("2024").startOf("year").valueOf(),
    //       endTime: this.$moment("2024").endOf("year").valueOf(),
    //     },
    //     {
    //       label: "2023年",
    //       value: "8",
    //       beginTime: this.$moment("2023").startOf("year").valueOf(),
    //       endTime: this.$moment("2023").endOf("year").valueOf(),
    //     },
    //     {
    //       label: "2022年",
    //       value: "7",
    //       beginTime: this.$moment("2022").startOf("year").valueOf(),
    //       endTime: this.$moment("2022").endOf("year").valueOf(),
    //     },
    //     {
    //       label: "2021年",
    //       value: "2",
    //       beginTime: this.$moment("2021").startOf("year").valueOf(),
    //       endTime: this.$moment("2021").endOf("year").valueOf(),
    //     },
    //     {
    //       label: "2020年",
    //       value: "3",
    //       beginTime: this.$moment("2020").startOf("year").valueOf(),
    //       endTime: this.$moment("2020").endOf("year").valueOf(),
    //     },
    //     {
    //       label: "2019年",
    //       value: "4",
    //       beginTime: this.$moment("2019").startOf("year").valueOf(),
    //       endTime: this.$moment("2019").endOf("year").valueOf(),
    //     },
    //     {
    //       label: "2018年",
    //       value: "5",
    //       beginTime: this.$moment("2018").startOf("year").valueOf(),
    //       endTime: this.$moment("2018").endOf("year").valueOf(),
    //     },
    //     {
    //       label: "2018年以前",
    //       value: "6",
    //       beginTime: this.$moment("1970").startOf("year").valueOf(),
    //       endTime: this.$moment("2017").endOf("year").valueOf(),
    //     },
    //   ]
    //   return boxInfoSelectOption
    // },
    // 去申请界面
    goApply() {
      this.$router.push({
        path: '/offshelf/apply'
      })
    },
    // 去审核界面
    goApprove() {
      this.$router.push({
        path: '/offshelf/approve'
      })
    },
    // 导出销毁记录
    outExcel() {
      this.isExcelLoading = true;
      axios({
        headers: {
          Authorization: JSON.parse(Cookies.get("userInfo")).token,
        },
        url: "/api/business/order/export",
        method: "post",
        responseType: "blob", // 后台响应数据类型
        data: this.exportData,
      }).then((response) => {
        this.isExcelLoading = false;
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        let fname =
          "永久下架记录_" +
          this.$moment(new Date()).format("YYYY-MM-DD") +
          ".xlsx";
        link.href = url;
        link.setAttribute("download", fname);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    },
    // 凭证弹窗展示
    toshowVoucher(type, row) {
      // 1 销毁清单  2 取消凭证
      if (type == 1) {
        this.voucherTitle = "下架凭证";
        // this.voucherList = [];
        getOrderFileList(row.id, 0).then((res) => {
          this.voucherList = res.data;
        });
      } else if (type == 2) {
        this.voucherTitle = "取消凭证";
        // this.voucherList = [];
        getOrderFileList(row.id, 3).then((res) => {
          this.voucherList = res.data;
        });
      } else if (type == 3) {
        this.voucherTitle = "销毁凭据";
        // this.voucherList = [];
        getOrderFileList(row.id, 2).then((res) => {
          this.voucherList = res.data;
        });
      }
      this.isShowVoucher = true;
    },
    // 关闭凭证展示
    closeVoucherDialog() {
      this.isShowVoucher = false;
    },
    // 头部筛选项变化
    changeSelect() {
      this.pageNum = 1;
      this.getOffshelfLogList();
    },

    // 订单中窍过多  加载更多
    showMore(row) {
      if (row.currentPage < row.totalPage) {
        row.currentPage++;
        getOrderBoxList({orderId: row.id, searchBoxCode: this.searchForm.keyword.trim()}, {pageSize: 5, pageNum: row.currentPage}).then((res) => {
          row.boxInfo = row.boxInfo.concat(res.data);
          this.$forceUpdate();
        });
      }
    },

    // 去窍详情
    goBoxDetail(row) {
      // this.$router.push({
      //   // name: "BoxDetail",
      //   name: 'OffshelfBoxDetail',
      //   params: {
      //     id: row.userBoxId,
      //   },
      // });
      let routeUrl = this.$router.resolve({
        name: "OffshelfBoxDetail",
        params: { id: row.userBoxId },
      });
      window.open(routeUrl.href, "_blank");
    },
    // 去 订单详情
    goOrderDetail(row) {
      // this.$router.push({
      //   name: "OrderDetail",
      //   params: {
      //     id: row.id,
      //   },
      // });
      let routeUrl = this.$router.resolve({
        name: "OrderDetail",
        params: { id: row.id, },
      });
      window.open(routeUrl.href, "_blank");
    },
    // 分页数据变动
    pageChange(emitData) {
      this.pageNum = emitData.pageNum;
      this.pageSize = emitData.pageSize;
      this.getOffshelfLogList();
    },
    // 取消窍 - 永久下架订单中有多个窍时取消单个窍
    cancelBox(row, box) {
      this.$confirm("是否确认取消当前的永久下架?", "确认", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then((res) => {
        const data = {
          files: [],
          id: row.id,
          userBoxId: box && box.userBoxId,
          // status: 3,
        }
        this.isLoading = true;

        new Promise((resolve) => {
          cancelReadOrder(data)
            .then((res) => {
              this.$message({
                type: "success",
                message: "取消永久下架成功",
              });

              this.getOffshelfLogList();
            })
            .catch((err) => {
              this.isLoading = false;
            });
        });
      });
    },
    // 获得永久下架记录
    getOffshelfLogList() {
      // 0调阅 1回库 2销毁 3永久下架
      let data = {
        type: 3,
        keyword: this.searchForm.keyword.trim(),

        userIdList: this.applyNameHeader ? [this.applyNameHeader] : [], // createdUserId   == 列表中 获得 userId
        status: this.statusHeader ? this.statusHeader : undefined,

        startTime:
          this.boxInfoHeader &&
          parseInt(
            this.commonFun.getBoxInfoSelectOption().filter(
              (e) => e.value == this.boxInfoHeader
            )[0].beginTime / 1000
          ),
        endTime:
          this.boxInfoHeader &&
          parseInt(
            this.commonFun.getBoxInfoSelectOption().filter(
              (e) => e.value == this.boxInfoHeader
            )[0].endTime / 1000
          ),
      };
      this.exportData = data;

      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      this.isLoading = true;
      new Promise((resolve) => {
        getOrderList(data, params)
          .then((res) => {
            res.data.map((e) => {
              e.createdOn = this.$moment(e.createdOn * 1000).format(
                "YYYY-MM-DD HH:mm:ss"
              );
              // e.boxInfo = e.boxList;
              e.canPeopleCancel =
                JSON.parse(localStorage.getItem("localUserInfo")).id ===
                e.userId;
            });
            this.backLogList = res.data;
            // this.total = res.total;
            getOrderListCount(data, params).then(resm => {
              this.total = resm
            })

            this.backLogList.map((e) => {
              getOrderBoxList({orderId: e.id, searchBoxCode: this.searchForm.keyword.trim()}, {pageSize: 5, pageNum: 1}).then((resB) => {
                e.boxInfo = resB.data;
                e.boxInfoLength = resB.total;
                // 记录当前订单中的总窍数 及 已显示的页数
                e.totalPage = Math.ceil(resB.total / 5);
                e.currentPage = 1;
                this.$forceUpdate();
              });
            });

            this.isLoading = false;
          })
          .catch((err) => {
            this.isLoading = false;
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.search-list {
  padding-top: 20px;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  ::v-deep .el-form {
    flex: 1;
  }
  .form-inline {
    ::v-deep .el-form-item {
      margin-bottom: 0;
      width: 100%;
    }
    ::v-deep  .el-form-item__content {
      width: 40%;
    }

    ::v-deep  .el-input-group__append {
      color: #fff;
      background-color: #f88123;
    }
  }

  .search-right {
    .btn {
      // display: flex;
      // justify-content: center;
      // align-items: center;
      // img {
      //   height: 15px;
      //   margin-right: 5px;
      // }
      span {
        font-size: 14px;
        margin-left: 3px;
        font-weight: bold;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
.box-code {
  width: 100%;
  .show-more {
    cursor: pointer;
    transform: translateY(-14px) translateX(-15px) rotate(90deg);
    color: #f88125;
    font-size: 16px;
    font-weight: bold;
  }
  .box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 10px;
    height: 100px;
    // margin: 10px 0;
    .box-code-left {
      cursor: pointer;
    }
    .access-detail {
      width: 150px;
      word-break: break-all;
      // 超出两行显示 ......
      text-overflow: -o-ellipsis-lastline;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
      text-align: left;
    }
    .box-operate {
      min-width: 62px;
    }
  }
  .border-right {
    border-right: 1px solid #cfcfcf;
  }
  .border-bottom {
    border-bottom: 1px solid #ebeef5;
  }
}
.hover-change {
  cursor: pointer;
}
.hover-change:hover {
  color: #f88123;
}

.popover-item {
  line-height: 20px;
  font-size: 12px;
  padding-left: 10px;
  i {
    margin-right: 8px;
  }
}
::v-deep  .el-popover__reference-wrapper {
  cursor: pointer;
}

.header-select-first {
  padding-left: 15px;
  width: 100%;
}
</style>
